
import os
from dashscope import Generation

# 从环境变量获取API密钥
api_key = os.getenv("DASHSCOPE_API_KEY")
if not api_key:
    api_key = "sk-2c036d80d14a443f8769e072bb09a2e1"

# 构建多轮对话的提示词
def create_conversation_prompt(history, language):
    prompt_parts = []
    
    # 添加历史对话
    for message in history:
        if hasattr(message, 'content'):
            if message.__class__.__name__ == 'HumanMessage':
                prompt_parts.append(f"Human: {message.content}")
            elif message.__class__.__name__ == 'AIMessage':
                prompt_parts.append(f"AI: {message.content}")
    
    # 添加新的翻译请求
    prompt_parts.append(f"Human: Translate your answer to {language}.")
    
    return "\n".join(prompt_parts)

# 模拟LangChain的消息对象
class HumanMessage:
    def __init__(self, content):
        self.content = content

class AIMessage:
    def __init__(self, content):
        self.content = content

# 创建消息历史
human_message = HumanMessage(content="Who is Elon Musk?")
ai_message = AIMessage(
    content="Elon Musk is a billionaire entrepreneur, inventor, and industrial designer"
)

# 构建完整的对话提示词
messages = [human_message, ai_message]
prompt = create_conversation_prompt(messages, "中文")

print("生成的对话历史:")
for msg in messages:
    print(f"{msg.__class__.__name__}: {msg.content}")
print(f"Human: Translate your answer to 中文.")
print("\n" + "="*50 + "\n")

try:
    # 使用DashScope进行对话
    response = Generation.call(
        model='qwen-plus',
        prompt=prompt,
        api_key=api_key
    )
    
    print("模型回复:")
    print(response.output.text)
    
except Exception as e:
    print(f"调用模型时出错: {e}")
    print("请检查API密钥")
